package com.base.data.elasticsearch.util.gson;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.introspect.AnnotationMap;
import com.base.data.elasticsearch.util.BaseDateUtil;

import java.io.IOException;
import java.util.Date;

public class JacksonDefaultDeserializerDate extends JsonDeserializer<Date> implements ContextualDeserializer {

    private String pattern = BaseDateUtil.DEFAULT_TIME_PATTER;

    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        return BaseDateUtil.parseDateWithPattern(jsonParser.getValueAsString(), pattern);
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext deserializationContext, BeanProperty beanProperty) throws JsonMappingException {
        AnnotationMap annotated = beanProperty.getMember().getAllAnnotations();

        JsonFormat jsonFormat = annotated.get(JsonFormat.class);
        if (jsonFormat != null && jsonFormat.pattern() != null) {
            pattern = jsonFormat.pattern();
        }
        return this;
    }
}
